package dbStruct;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import dbStruct.Node.NodeType;
import edu.umd.cs.piccolo.PNode;

public class Nodes {
	private static Nodes instance;
	private HashMap<String, Node> nodes;
	
	public static Nodes getInstance()	{
		if(instance==null) instance=new Nodes();
		return instance;
	}
	public Nodes()	{
		super();
		nodes=new HashMap<String, Node>();
	}
	public void add(Node node){
		String name = node.getName();
		nodes.put(name, node);
	}
	public Node remove(String name){
		Node Node = nodes.get(name);
		nodes.remove(name);
		return Node;
	}
	public Node get(String name)	{
		return nodes.get(name);
	}
	public boolean exists(Node Node){
		return nodes.containsValue(Node);
	}
	public boolean exists(String name){
		return nodes.containsKey(name);
	}
	public void clear(){
		nodes.clear();
	}
	public Vector<Node> getNodes(NodeType type)	{
		Vector<Node> tables = new Vector<Node>();
		Iterator<Node> it = this.nodes.values().iterator();
		while(it.hasNext())
		{
			Node node = it.next();
			if(node.getType()==type)
				tables.add(node);
		}
		return tables;
	}
	public Vector<Node> getTables()	{
		return getNodes(NodeType.TABLE);
	}
	public Vector<Node> getColumns(String tableName)	{
		Vector<Node> nodes = DatabaseStructure.getInstance().getConnectors().getColumns(tableName);
		return nodes;
	}
	public Node getNodeFromPNode(PNode pnode)
	{
		Node node = null;
		Iterator<Node> it = nodes.values().iterator();
		while(it.hasNext())
		{
			node = it.next();
			System.out.println("controllo nodo " + node.getName());
			try {
				if(node.getNode().equals(pnode))
					return node;
			} catch (NullPointerException e) {
				return null;
			}
				
		}
		return null;
	}
}
